import 'dart:math';

import 'package:bottom_picker/bottom_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutterproject/page/mine/children/assets/childdren/formatter.dart';
import 'package:flutterproject/page/mine/children/assets/data/zengzhi_bean.dart';
import 'package:flutterproject/util/address_manager.dart';
import 'package:flutterproject/util/dialog_toast/dialog_util.dart';
import 'package:flutterproject/util/dialog_toast/toast_util.dart';
import 'package:flutterproject/util/extension/extension_util.dart';
import 'package:flutterproject/util/extension/widget_extension.dart';
import 'package:flutterproject/util/http/http_client.dart';
import 'package:flutterproject/util/http/http_exception.dart';
import 'package:flutterproject/util/margin_padding_util.dart';
import 'package:flutterproject/widget/app_bar_common.dart';
import 'package:flutterproject/widget/button_common.dart';
import 'package:flutterproject/widget/image_extended.dart';
import 'package:flutterproject/widget/text/text_common.dart';
import 'package:flutterproject/widget/text/text_field_common.dart';
import 'package:get/get.dart';

import 'zengzhi_history.dart';

class ZengZhi extends StatefulWidget {
  final VoidCallback callback;

  const ZengZhi({Key? key, required this.callback}) : super(key: key);

  @override
  State<ZengZhi> createState() => _ZengZhiState();
}

class _ZengZhiState extends State<ZengZhi> {
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController moneyController =
      TextEditingController(text: "0");

  ZengzhiBean? bean;

  ZengzhiList? item;

  HttpClient client = Get.find<HttpClient>();

  bool isExpand = false;

  @override
  void initState() {
    super.initState();
    getConfig();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        ColoredBox(
          color: Color(0xFFF6F6F6),
          child: Column(
            children: [
              AppBarCommon(
                title: "创投积分增值",
                bgColor: Color(0xFFEDC88B),
                leftColor: Colors.white,
                titleColor: Colors.white,
              ),
              Container(
                margin: MarginPaddingUtil.only(top: 78, left: 40, right: 40),
                padding: MarginPaddingUtil.fromLTRB(
                    left: 30, top: 47, right: 30, bottom: 61),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20.radius),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    TextCommon(
                      "增值方案",
                      size: 28.sp,
                      color: Color(0xFF414141),
                    ),
                    30.heightBox,
                    _buildBg(
                        child: TextCommon(
                          item?.title ?? "",
                          size: 28.sp,
                          color: Colors.black,
                        ),
                        textEditingController: phoneController,
                        showRight: true),
                    66.heightBox,
                    Row(
                      children: [
                        TextCommon(
                          "投入额度",
                          size: 28.sp,
                          color: Color(0xFF414141),
                        ),
                        Spacer(),
                        TextCommon(
                          "创投积分余额：${bean?.balance}",
                          size: 28.sp,
                          color: Color(0xFFEDC88B),
                        ),
                        50.widthBox,
                      ],
                    ),
                    30.heightBox,
                    _buildBg(
                        child: SizedBox.shrink(),
                        textEditingController: moneyController,
                        inputFormatters: [InputFormatter()]),
                    66.heightBox,
                    Align(
                      child: ButtonCommon(
                        text: "确定",
                        onTap: () => showPwdDialog(),
                        width: 472.width,
                        color: Color(0xFFEDC88B),
                        borderRadios: 30.radius,
                        fontColor: Colors.white,
                        fontSize: 36.sp,
                        fontWeight: FontWeight.bold,
                        padding: MarginPaddingUtil.symmetric(vertical: 20),
                      ),
                    ),
                  ],
                ),
              ),
              30.heightBox,
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildBg({
    required Widget child,
    required TextEditingController textEditingController,
    List<TextInputFormatter>? inputFormatters,
    bool showRight = false,
  }) {
    return Container(
      width: Get.width,
      padding: MarginPaddingUtil.symmetric(vertical: 24, horizontal: 40),
      decoration: BoxDecoration(
        color: Color(0xFFF6F6F6),
        borderRadius: BorderRadius.circular(32.radius),
      ),
      child: Row(
        children: [
          child,
          if (showRight)
            Expanded(
              child: SizedBox(
                height: 72.height,
                child: Row(
                  children: [
                    Spacer(),
                    Transform.rotate(
                      angle: isExpand ? pi : 0,
                      child: ImageCommon(
                        "/icon/arrow-down",
                        width: 25.width,
                        height: 20.height,
                      ),
                    ),
                  ],
                ),
              ).addClickEvent(() {
                BottomPicker(
                  items: bean?.list
                      ?.map((e) => Text(
                    e.title ?? "",
                    textAlign: TextAlign.center,
                  ))
                      .toList() ??
                      [],
                  title: '',
                  pickerTextStyle: TextStyle(
                      color: Colors.black,
                      fontSize: 24.sp,
                      fontWeight: FontWeight.bold,
                      height: 2.2),
                  dismissable: true,
                  displayButtonIcon: false,
                  buttonText: "确定",
                  buttonTextStyle: TextStyle(
                    color: Colors.black,
                    fontSize: 24.sp,
                    fontWeight: FontWeight.bold,
                  ),
                  buttonSingleColor: Colors.grey.withOpacity(0.5),
                  onSubmit: (_) {
                    item = bean?.list![_];
                    setState(() {});
                  },
                ).show(context);
              }),
            ),
          if (!showRight)
            Expanded(
                child: TextFieldCommon(
              controller: textEditingController,
              height: 72.width,
              size: 50.sp,
              textColor: Colors.black,
              padding: MarginPaddingUtil.symmetric(horizontal: 25),
              inputFormatters: inputFormatters,
              keyboardType: TextInputType.number,
            ))
        ],
      ),
    );
  }

  void showPwdDialog() {
    DialogUtil.showPwdDialog((value) {
      confirm(value);
    });
  }

  Future<bool> getConfig() async {
    try {
      DialogUtil.showLoading();
      bean = await client.get<ZengzhiBean>(
        AddressManager.zengzhiConfig,
      );
      if (bean?.list?.isNotEmpty ?? false) {
        item = bean?.list![0];
      }
      setState(() {});
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }

  Future<bool> confirm(String pwd) async {
    try {
      DialogUtil.showLoading();
      await client.post(AddressManager.zengzhiCreate, data: {
        "password": pwd,
        "type": item?.type,
        "value": moneyController.text
      });
      widget.callback();
      Get.off(ZengZhiHistory());
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }
}
